# _*_ encoding:utf-8 _*_

import matplotlib
matplotlib.use('TkAgg')

import matplotlib.pyplot as plt
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


def get_lines(filename):
    lines = []
    for event, elem in ET.iterparse(filename):
        if event == 'end':
            if elem.tag == 'lane':
                # get shape
                shapes = elem.attrib['shape']
                points = shapes.split(' ')
                line = []
                for point in points:
                    x, y = map(float, point.split(','))
                    # print('{0}, {1}'.format(x, y))
                    line.append((x, y))
                lines.append(line)
    return lines


def get_edges(filename):
    edges = []
    tree = ET.ElementTree(file=filename)
    for child_of_root in tree.getroot():
        if child_of_root.tag == 'edge':
            # parse the first lane
            shapes = child_of_root[0].attrib['shape']
            points = shapes.split(' ')
            line = []
            for point in points:
                x, y = map(float, point.split(','))
                line.append((x, y))
            edges.append(line)
    return edges


def write_file(dataset, filename, format_, mode='wb'):
    fp = open(filename, mode)
    for item in dataset:
        fp.write(format_(item))
    fp.close()


def format_line(line):
    points = []
    for point in line:
        points.append("{0},{1}".format(point[0], point[1]))
    str = ' '.join(points)
    return str + '\n'


def load_from_file(filename, parse_):
    fp = open(filename, 'rb')
    dataset = []
    for line in fp.readlines():
        elements = parse_(line)
        dataset.append(elements)
    return dataset


def parse_line(line):
    points = []
    for point in line.spilt(' '):
        x, y = map(float, point.split(','))
        points.append((x, y))
    return points


def plot_map(dataset):
    for line in dataset:
        x = [point[0] for point in line]
        y = [point[1] for point in line]
        plt.plot(x, y)
    plt.show()


def main():
    read_file = '../../data/hangzhou1.net.xml'
    write_name = '../../data/hangzhou.map.txt'
    # lines = get_lines(read_file)
    lines = get_edges(read_file)
    print 'line len {0}'.format(len(lines))
    plot_map(lines)
    # write_file(lines, write_name, format_line, mode='w')


if '__main__' == __name__:
    main()
